#include <glib-2.0/glib/glist.h>
#include <glib-2.0/glib/gthread.h>
#include <glib-2.0/glib/gtypes.h>
#include "glist_ts.h"

// appendo in coda
GList* g_list_append_ts(GList* list, gpointer data, GStaticRWLock* lock)
{
    g_static_rw_lock_writer_lock(lock);
    list = g_list_append(list, data);
    g_static_rw_lock_writer_unlock(lock);
    return list;
}
// insermento ordinato
GList* g_list_insert_sorted_ts(GList* list, gpointer data, GCompareFunc func, GStaticRWLock* lock)
{
    g_static_rw_lock_writer_lock(lock);
    list = g_list_insert_sorted(list, data, func);
    g_static_rw_lock_writer_unlock(lock);
    return list;
}
GList * g_list_insert_inqueue_ts(GList * list, gpointer data, GStaticRWLock * lock)
{
    g_static_rw_lock_writer_lock(lock);
    list = g_list_insert(list,data,-1);
    g_static_rw_lock_writer_unlock(lock);
    return list;
}
// restituisce il numero di elementi in lista
guint g_list_length_ts(GList* list, GStaticRWLock* lock)
{
    guint lenght;
    g_static_rw_lock_reader_lock(lock);
    lenght = g_list_length(list);
    g_static_rw_lock_reader_unlock(lock);
    return lenght;
}
// restituzione elemento in posizione pos
gpointer g_list_get_element_at_ts(GList* list, guint pos, GStaticRWLock* lock)
{
    gpointer data;
    guint l = g_list_length_ts(list, lock);
    if(pos >= l)
    {
        data = NULL;
        return data;
    }
    g_static_rw_lock_reader_lock(lock);
    data = g_list_nth_data(list, pos);
    g_static_rw_lock_reader_unlock(lock);
    return data;
}
// ricerca di un elemento
GList* g_list_find_custom_ts(GList* list, gpointer data, GCompareFunc func, GStaticRWLock* lock)
{
    GList* find;
    g_static_rw_lock_reader_lock(lock);
    find = g_list_find_custom(list, data, func);
    g_static_rw_lock_reader_unlock(lock);
    return find;
}
// rimozione senza free
GList* g_list_remove_custom_ts(GList* list, gpointer data, GCompareFunc func, GStaticRWLock* lock)
{
    GList *find = g_list_find_custom_ts(list, data, func, lock);
    if(find != NULL)
    {
        g_static_rw_lock_writer_lock(lock);
        list = g_list_remove_link(list, find);
        g_static_rw_lock_writer_unlock(lock);
    }
    return list;
}
